<?php


namespace App\Admin\Actions\Post;


use App\Admin\Actions\RowAction;
use App\Models\AdminUser;
use App\Transverse;
use Encore\Admin\Actions\Response;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class TransverseBillPost extends RowAction
{
    public $name = '到账';

    public function handle(Transverse $model, Request $request): Response
    {
        $amount = $request->get('amount');
        if (!is_numeric($amount) || $amount <= 0) {
            $this->response()->status = false;
            return $this->response()->error('请填写有效金额');
        }
        $total = $model->bills()->sum('amount');
        $in_amount = $total + $amount;
        if ($in_amount > $model['amount']) {
            $this->response()->status = false;
            return $this->response()->error('到账总金额不能大于合同金额');
        }
        $user = Admin::user();
        $model->bills()->create([
            'amount'     => $amount,
            'pay_date'   => $request->get('pay_date'),
            'creator_id' => $user['id']
        ]);
        $model->in_amount = $in_amount;
        $model->save();
        $model->writeLog($user, '【到账】新增',  $amount);
        return $this->response()->success('操作成功')->refresh();
    }

    public function form()
    {
        $this->text('amount', '到账金额(万)')->rules('required');
        $this->date('pay_date', '到账时间')->rules('required', ['required' => '到账时间不能为空']);
    }

    public function authorize(AdminUser $user, $model): bool
    {
        return $user->role_type == 1;
    }
}
